package cn.itcast.consumer.web;

import cn.itcast.consumer.clients.UserClient;
import cn.itcast.consumer.config.RedisProperties;
import cn.itcast.consumer.pojo.Result;
import cn.itcast.consumer.pojo.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Random;

@RestController
@RequestMapping("consumer")
public class ConsumerController {
//    @Autowired
//    private RestTemplate restTemplate;


    @Autowired
    private UserClient userClient;

    @Autowired
    private RedisProperties properties;

    @GetMapping("prop")
    public RedisProperties getProperties(){
        return properties;
    }

    @GetMapping("{id}")
    public User queryById(@PathVariable("id") Long id){
        return userClient.queryById(id);
    }

//    //负载均衡
//    //第三步添加注解，开启线程隔了功能
//    @HystrixCommand(fallbackMethod = "queryByIdFallback",commandProperties = {
//            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
//            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000")
//    })//声明降级逻辑的方法
//    @GetMapping("{id}")
//    public Result queryById(@PathVariable("id") Long id){
//        if(id==1){
//            throw new RuntimeException("你个倒霉蛋");
//        }
//        String url="http://user-service/user/"+id;
//
//        User user = restTemplate.getForObject(url, User.class);
//        return Result.success(user);
//
//    }

    //第四步编写降级逻辑
    public Result queryByIdFallback(Long id){
        return Result.error("服务器繁忙，稍后再试");
    }

//    @Autowired
//    private DiscoveryClient discoveryClient;
//
//    @GetMapping("{id}")
//    public User queryById(@PathVariable("id") Long id) {
//
//        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
//
//        int i = new Random().nextInt(instances.size());
//        i = (i + 1) % instances.size();
//        ServiceInstance instance = instances.get(i);
//        //获取ip
//        String host = instance.getHost();
//        //获取端口号
//        int port = instance.getPort();
//
//        String url = "http://"+host+":"+port+"/user/" + id;
//        User user = restTemplate.getForObject(url, User.class);
//        return user;
//
//    }

}
